package lc20240515;

//289.生命游戏
public class Demo3 {
    public static void main(String[] args) {
        int[][] board = {
            {0, 1, 0},
            {0, 0, 1},
            {1, 1, 1},
            {0, 0, 0}
        };

        gameOfLife(board);
        printBoard(board);
    }

    public static void gameOfLife(int[][] board) {
        int rows = board.length;
        int cols = board[0].length;

        //做好标记
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int liveNeighbors = countLiveNeighbors(board, i, j);

                // Rule 1 or Rule 3
                if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
                    board[i][j] = 2; // Alive to Dead
                }

                // Rule 4
                if (board[i][j] == 0 && liveNeighbors == 3) {
                    board[i][j] = 3; // Dead to Alive
                }
            }
        }

        //一次进化
        // Update the board to the next state
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (board[i][j] == 2) {
                    board[i][j] = 0;
                } else if (board[i][j] == 3) {
                    board[i][j] = 1;
                }
            }
        }
    }

    private static int countLiveNeighbors(int[][] board, int row, int col) {
        //计算八个位置的状态
        int[] directions = {-1, 0, 1};
        int liveNeighbors = 0;

        for (int i = 0; i < directions.length; i++) {
            for (int j = 0; j < directions.length; j++) {
                if (directions[i] == 0 && directions[j] == 0) continue;

                int r = row + directions[i];
                int c = col + directions[j];

                //注意边界条件。
                if (r >= 0 && r < board.length && c >= 0 && c < board[0].length) {
                    //计算活细胞的数量，因为等于2表示即将从活变死，但是当前仍是活细胞的状态。
                    if (board[r][c] == 1 || board[r][c] == 2) {
                        liveNeighbors++;
                    }
                }
            }
        }

        return liveNeighbors;
    }

    private static void printBoard(int[][] board) {
        for (int[] row : board) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }
    }
}
